package be.vdab.filter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class ServletFilter
 */
@WebFilter("*.htm")
public class ServletFilter implements Filter {
	private final static String STATISTIEK = "statistiek";
	  @Override
	  public void init(FilterConfig filterConfig) throws ServletException {
	    filterConfig.getServletContext().setAttribute("statistiek",
	      new ConcurrentHashMap<String, Integer>());
	  }
	  @Override
	  public void doFilter(ServletRequest request, ServletResponse response,
	    FilterChain chain) throws IOException, ServletException {
	    if (request instanceof HttpServletRequest) {
	      String url = ((HttpServletRequest) request).getRequestURI();
	      int index = url.indexOf(";jsessionid=");
	      if (index != -1) {
	        url = url.substring(0, index);
	      }
	      voegRequestToe(url, request.getServletContext());
	    }
	    chain.doFilter(request, response);
	  }
	  private void voegRequestToe(String url, ServletContext context) {
	    @SuppressWarnings("unchecked")
	    Map<String, Integer> statistiek = 
	      (Map<String, Integer>) context.getAttribute(STATISTIEK);
	    if (statistiek.containsKey(url)) {
	      statistiek.put(url, statistiek.get(url) + 1);
	    } else {
	      statistiek.put(url, 1);
	    }
	  }
	  @Override
	  public void destroy() {
	  }


}
